package com.formula.propertyshop.view.phone;

import java.io.ByteArrayOutputStream;
import java.util.List;

import android.content.Intent;
import android.graphics.Bitmap;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.formula.propertyshop.R;
import com.formula.propertyshop.adapter.FeedbackTemplateSpinnerAdapter;
import com.formula.propertyshop.model.Feedback;
import com.formula.propertyshop.model.FeedbackTemplate;
import com.formula.propertyshop.model.POSTResponse;
import com.formula.propertyshop.service.IWireFrameService;
import com.formula.propertyshop.service.WireFrameServiceFactory;
import com.formula.propertyshop.utils.Const;
import com.formula.propertyshop.utils.DeviceInfo;
import com.formula.propertyshop.utils.WFErrorCode;
import com.formula.propertyshop.utils.WFUtils;
import com.formula.propertyshop.view.common.BaseActivity;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.CancelableCallback;
import com.google.android.gms.maps.GoogleMap.OnMarkerDragListener;
import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class FeedBackActivity extends BaseActivity
	implements
	ConnectionCallbacks,
	OnConnectionFailedListener,
	LocationListener,
	OnMyLocationButtonClickListener,
	OnMarkerDragListener
{
	private Spinner cbbTamplate;
	private ImageView imgPicture;
	private ImageButton btnCamera;
	private Button btnSend;
	private Bitmap bmMarker;
	private TextView txtEmail;
	private TextView txtName;
	private TextView txtPhone;
	private SupportMapFragment mapFragment;
	//private CustomInfoWindowAdapter markerInforAdapter;
	private static final String IMAGEVIEW_TAG = "The Android Logo";
	 // Bundle keys.
    private static final String MARKER_POSITION = "markerPosition";
    private static final String MARKER_ICON = "markerIcon";
	private Location currentLocation = null;
	private Marker currentMarker = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		 if(!WFUtils.checkInternetConnection(this)){
	        	showNetworkErrorDlg();
	        	finish();
			return;
		}
		if(!WFUtils.checkLocationService(this)){
			showLocationSettingDlg(R.string.msg_location_not_enabled);
		}
		
		setControls();
		loadData();
		createMapIfReady();
		if(savedInstanceState!=null){
			LatLng l = savedInstanceState.getParcelable(MARKER_POSITION);
			bmMarker = savedInstanceState.getParcelable(MARKER_ICON);
			currentMarker = drawMarker(bmMarker,l);
			//currentMarker.showInfoWindow();
		}
	}
	 @Override
     public void onSaveInstanceState(Bundle outState) {
         super.onSaveInstanceState(outState);

         // All Parcelable objects of the API  (eg. LatLng, MarkerOptions, etc.) can be set
         // directly in the given Bundle.
         if(currentLocation!=null)
        	 outState.putParcelable(MARKER_POSITION, new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()));
         if(bmMarker!=null)
         {      	 
        	 outState.putParcelable(MARKER_ICON, bmMarker);
         }
     }
	 
	private void setControls(){
		
		btnCamera.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

			    // start the image capture Intent
			    startActivityForResult(intent, Const.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);

			}
		});
		
		btnSend.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				saveData();
				handleSendFeedback();
			}
		});
        
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	    if (requestCode == Const.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
	        if (resultCode == RESULT_OK) {	            
	            try {					        
	            	Bitmap bmSr = (Bitmap) data.getExtras().get("data");	           	
	            	bmMarker = Bitmap.createScaledBitmap(bmSr, DeviceInfo.convertDPIToPixel(Const.IMAGEVIEW_SIZE_FEEDBACK), DeviceInfo.convertDPIToPixel(Const.IMAGEVIEW_SIZE_FEEDBACK), false);
	            	bmSr.recycle();
	            	bmSr = null;
	            	imgPicture.setImageBitmap(bmMarker);
	            	LatLng currLng = null;
	            	if (currentLocation != null) {
	        			currLng = new LatLng(
	        					currentLocation.getLatitude(),
	        					currentLocation.getLongitude());
	            	}
	            	currentMarker = drawMarker(bmMarker,currLng);
	            	//currentMarker.showInfoWindow();
	            	
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
	            
	        } else if (resultCode == RESULT_CANCELED) {
	            // User cancelled the image capture
	        } else {
	            // Image capture failed, advise user
	        }
	    }
	}
	private GoogleMap mMap;
	private LocationClient mLocationClient;
	 // These settings are the same as the settings for the map. They will in fact give you updates
    // at the maximal rates currently possible.
    private static final LocationRequest REQUEST = LocationRequest.create()
            .setInterval(5000)         // 5 seconds
            .setFastestInterval(16)    // 16ms = 60fps
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
	 
    private void createMapIfReady() {
	        // Do a null check to confirm that we have not already instantiated the map.
	        if (mMap == null) {
	            // Try to obtain the map from the SupportMapFragment.
	            mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
	            mMap = mapFragment.getMap();
	            if (mMap != null) {
	                mMap.setMyLocationEnabled(true);
	                mMap.setOnMyLocationButtonClickListener(this);
	                mMap.setOnMarkerDragListener(this);
	                //markerInforAdapter = new CustomInfoWindowAdapter(this);
	        		//mMap.setInfoWindowAdapter(markerInforAdapter);
	            }
	        }
	    }
    private void setUpLocationClientIfNeeded() {
        if (mLocationClient == null) {
            mLocationClient = new LocationClient(
                    getApplicationContext(),
                    this,  // ConnectionCallbacks
                    this); // OnConnectionFailedListener
            
        }
    }
    @Override
    public void onPause() {
        super.onPause();
        if (mLocationClient != null) {
            mLocationClient.disconnect();
        }
    }
    @Override
    public void onResume() {
        super.onResume();

        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
        
        if (resultCode == ConnectionResult.SUCCESS){
        /* Toast.makeText(getApplicationContext(), 
           "isGooglePlayServicesAvailable SUCCESS", 
           Toast.LENGTH_LONG).show();*/
        }else{
         GooglePlayServicesUtil.getErrorDialog(resultCode, this, Const.RQS_GooglePlayServices).show();
        }
        createMapIfReady();
        setUpLocationClientIfNeeded();
        mLocationClient.connect();
    }
	@Override
	public boolean onMyLocationButtonClick() {
		if(!WFUtils.checkGPSisEnable(this)){
			showLocationSettingDlg(R.string.msg_GPS_not_enabled);
		}
		//Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
        // Return false so that we don't consume the event and the default behavior still occurs
        // (the camera animates to the user's current position).
        return false;
	}
	@Override
	public void onLocationChanged(Location arg0) {
		currentLocation = arg0;
		if(currentMarker!=null)
			return;
		try{
			 LatLng currLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
			 currentMarker = drawMarker(null, currLng);
	        CameraPosition currPos =
	                new CameraPosition.Builder().target(currLng)
	                        .zoom(15.5f)
	                        .bearing(0)
	                        .tilt(25)
	                        .build();
	        changeCamera(currPos);
	        mLocationClient.removeLocationUpdates(this);
		}catch(Exception ex){
			ex.printStackTrace();
		}
        
	}
	@Override
	public void onConnectionFailed(ConnectionResult result) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onConnected(Bundle connectionHint) {
		 mLocationClient.requestLocationUpdates(
	                REQUEST,
	                this);  // LocationListener
		 
		 
	}
	@Override
	public void onDisconnected() {
		// TODO Auto-generated method stub
		
	}
	/**
     * Change the camera position by moving or animating the camera depending on the state of the
     * animate toggle button.
     */
    private void changeCamera(CameraPosition position) {
    	mMap.animateCamera(CameraUpdateFactory.newCameraPosition(position), new CancelableCallback() {
             @Override
             public void onFinish() {
                 /*Toast.makeText(getBaseContext(), "Animation to Sydney complete", Toast.LENGTH_SHORT)
                         .show();*/
             }

             @Override
             public void onCancel() {
               /*  Toast.makeText(getBaseContext(), "Animation to Sydney canceled", Toast.LENGTH_SHORT)
                         .show();*/
             }
         });
        
    }
    private Marker drawMarker(Bitmap bm, LatLng currLng){
    	if(currLng==null)
    		currLng = mMap.getCameraPosition().target;
    	MarkerOptions mk = new MarkerOptions();
    	mk.draggable(true);
		mk.title(getString(R.string.current_location));
		mk.snippet(currLng.latitude+"_"+currLng.longitude);
		mMap.clear();
		try {
			String location = WFUtils.getAdressFromLocation(this, currLng);
			mk.snippet(location);			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mk.position(currLng);
		//markerInforAdapter.setIcon(bm);
		Marker marker = mMap.addMarker(mk);
		return marker;
    }
	@Override
	protected void initUI() {
		setContentView(R.layout.feedback_main);
		cbbTamplate = (Spinner) findViewById(R.id.cbbfeedback_template);
		TextView title = (TextView) findViewById(R.id.txtTitle);
		title.setText(getString(R.string.feedback));
		imgPicture = (ImageView) findViewById(R.id.imgView);
		btnCamera = (ImageButton) findViewById(R.id.btnCamera);
		btnSend = (Button) findViewById(R.id.btnSend);
		txtPhone = (TextView) findViewById(R.id.txtPhone);
		txtName = (TextView) findViewById(R.id.txtName);
		txtEmail = (TextView) findViewById(R.id.txtEmail);
		imgPicture.setTag(IMAGEVIEW_TAG);
	}
	private void loadData(){
		String name = WFUtils.getValue(this, Const.NAME_KEY);
		String email = WFUtils.getValue(this,Const.EMAIL_KEY);
		if(email.isEmpty())
			email = WFUtils.getPrimaryEmail(this);
		String phone = WFUtils.getValue(this, Const.PHONE_KEY);
		if(phone.isEmpty())
			phone = WFUtils.getPhoneNumber(this);
		txtName.setText(name);
		txtEmail.setText(email);
		txtPhone.setText(phone);
		showProgressDlg();
		Thread thread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				Message msg = mhandler.obtainMessage();
				List<FeedbackTemplate> templates = null;
				try {
					templates = WireFrameServiceFactory.getInstance().getService().getFeedbackTemplate();
				} catch (Exception e) {
					msg.arg1 = WFErrorCode.NETWORK_ERROR.getValue();
					e.printStackTrace();
				}
				
				msg.obj = templates;
				mhandler.sendMessage(msg);
			}
		});
		thread.start();
	}
	private Handler mhandler = new Handler(){
		@SuppressWarnings("unchecked")
		public void handleMessage (Message msg){
			dismissProgressDlg();
			if(msg.arg1==WFErrorCode.NETWORK_ERROR.getValue()){
				showNetworkErrorDlg();
				return;
			}
			if(msg.obj!=null){
				List<FeedbackTemplate> obj = (List<FeedbackTemplate>) msg.obj;
				FeedbackTemplateSpinnerAdapter adapterTerm =  new FeedbackTemplateSpinnerAdapter(FeedBackActivity.this,android.R.layout.simple_spinner_item,obj);
				adapterTerm.setDropDownViewResource(R.layout.dropdown_item);
				cbbTamplate.setAdapter(adapterTerm);
			}
		}
	};
	private void saveData(){
		String name = txtName.getText().toString();
		String email = txtEmail.getText().toString();
		String phone = txtPhone.getText().toString();
		WFUtils.saveValue(this, Const.NAME_KEY, name);
		WFUtils.saveValue(this, Const.PHONE_KEY, phone);
		WFUtils.saveValue(this, Const.EMAIL_KEY, email);
	}
	private boolean validateData(){
		Animation animFadein = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.sequence_button);  
		
		if(bmMarker == null){
			Toast.makeText(this, R.string.msg_capture_image, Toast.LENGTH_SHORT).show();
			btnCamera.startAnimation(animFadein);
			return false;
		}
		if(txtName.getText().toString().isEmpty()){
			Toast.makeText(this, R.string.msg_field_not_empty, Toast.LENGTH_SHORT).show();
			txtName.startAnimation(animFadein);
			return false;
		}
		if(txtPhone.getText().toString().isEmpty()){
			Toast.makeText(this, R.string.msg_field_not_empty, Toast.LENGTH_SHORT).show();
			txtPhone.startAnimation(animFadein);
			return false;
		}
		if(txtEmail.getText().toString().isEmpty()){
			Toast.makeText(this, R.string.msg_field_not_empty, Toast.LENGTH_SHORT).show();
			txtEmail.startAnimation(animFadein);
			return false;
		}
		return true;
	}
	private void handleSendFeedback(){
		if(!validateData())
			return;
		showProgressDlg();
		final Feedback fb = new Feedback();
		fb.email = txtEmail.getText().toString();
		fb.name = txtName.getText().toString();
		fb.phone = txtPhone.getText().toString();
		if(currentMarker!=null){
			fb.latitude = currentMarker.getPosition().latitude+"";
			fb.longitude = currentMarker.getPosition().longitude+"";
		}
		FeedbackTemplate feedbackTemplate = (FeedbackTemplate) cbbTamplate.getSelectedItem();
		fb.TemplateId = feedbackTemplate.getId()+"";
		if(bmMarker!=null){
			ByteArrayOutputStream stream = new ByteArrayOutputStream();
			bmMarker.compress(Bitmap.CompressFormat.PNG, 100, stream);
			byte[] byteArray = stream.toByteArray();
			String dataEncode = Base64.encodeToString(byteArray, Base64.DEFAULT);
			fb.imageData = dataEncode;
		}
		Thread thread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				Message msg= handler.obtainMessage();
				IWireFrameService service = WireFrameServiceFactory.getInstance().getService();						
				try {
					POSTResponse response = service.sendFeedback(fb);
					msg.obj = response;
				} catch (Exception e) {
					e.printStackTrace();
					msg.arg1 = WFErrorCode.NETWORK_ERROR.getValue();
				}
				handler.sendMessage(msg);
			}
		});
		thread.start();
	}
	private Handler handler = new Handler(){
		public void handleMessage (Message msg){
			dismissProgressDlg();
			if(msg.arg1 == WFErrorCode.NETWORK_ERROR.getValue()){
				showNetworkErrorDlg();
				return;
			}
			else if(msg.obj!=null){
				POSTResponse reponse = (POSTResponse) msg.obj;
				if(reponse.isResult()){
					Toast.makeText(FeedBackActivity.this, R.string.send_feedback_sucess, Toast.LENGTH_SHORT).show();
					finish();
				}
				else{
					Toast.makeText(FeedBackActivity.this, R.string.send_feedback_unsucess, Toast.LENGTH_SHORT).show();
				}
			}
		}
	};
	@Override
	public void onMarkerDrag(Marker arg0) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onMarkerDragEnd(Marker marker) {
		currentMarker = marker;
		try {
			String location = WFUtils.getAdressFromLocation(this, marker.getPosition());
			marker.setSnippet(location);
			marker.showInfoWindow();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	@Override
	public void onMarkerDragStart(Marker arg0) {
		// TODO Auto-generated method stub
		
	}
}
